package login_service_v1

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"log"
	"project-common/errs"
	"project-common/logs"
	"project-common/validate"
	"project-user/pkg/dao"
	"project-user/pkg/model"
	"project-user/pkg/repo"
	"runtime"
	"time"
)

type LoginService struct {
	UnimplementedLoginServiceServer
	cache repo.Cache
}

func New() *LoginService {
	return &LoginService{
		cache: dao.Rc,
	}
}

func (ls *LoginService) GetCaptcha(ctx context.Context, request *CaptchaRequest) (*CaptchaResponse, error) {
	// 获取参数
	mobile := request.Mobile
	log.Printf("system is %s \n", runtime.GOOS)

	// 参数校验
	if !validate.VerifyMobile(mobile) {
		return nil, errs.GrpcError(model.NoLegalMobile)
	}
	// 生成验证码
	code := "123456"
	// 调用短信平台（三方，放入go协程中执行）
	go func() {
		time.Sleep(2 * time.Second)
		zap.L().Info("短信平台调用成功，发送短信 [INFO]")
		logs.LG.Debug("短信平台调用成功，发送短信 [DEBUG]")
		zap.L().Error("短信平台调用成功，发送短信 [ERROR]")
		c, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()
		err := ls.cache.Put(c, fmt.Sprintf("REGISTER_%s", mobile), code, 15*time.Minute)
		if err != nil {
			log.Printf("验证码存入redis出错，cause by: %v \n", err)
		}
	}()
	// 存储验证码，redis中，过期时间15分钟
	return &CaptchaResponse{Code: code}, nil
}
